import { View, Canvas, ScrollView } from '@tarojs/components'
import { useState, useEffect, useRef } from 'react'
import Taro from '@tarojs/taro'
import { ui, isH5 } from '../../utils/platform'
import { getEmotionChartData, getEmotionPageList } from '../../services/api'
import EChartsComponent from './EChartsComponent'
import './index.less'

export default function EmotionChart({ visible, onClose }) {
  const [chartData, setChartData] = useState([])
  const [listData, setListData] = useState([])
  const [loading, setLoading] = useState(false)
  const [chartType, setChartType] = useState('line') // 'line' 或 'bar'
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize] = useState(10)
  const [total, setTotal] = useState(0)
  const [listLoading, setListLoading] = useState(false)
  const [selectedDays, setSelectedDays] = useState(7) // 默认7天
  const canvasRef = useRef(null)

  // 天数选项
  const daysOptions = [
    { label: '3天', value: 3 },
    { label: '7天', value: 7 },
    { label: '15天', value: 15 },
    { label: '30天', value: 30 }
  ]

  // 获取情感数据
  const fetchEmotionData = async (days = selectedDays) => {
    setLoading(true)
    try {
      const result = await getEmotionChartData(20, days)
      if (result.code === 100200) {
        // 处理数据，按时间排序，修复iOS日期格式兼容性
        const sortedData = result.data.sort((a, b) => {
          // 将 "2025-08-01 23:44:38" 格式转换为 "2025/08/01 23:44:38"
          const timeA = a.createTime.replace(/-/g, '/')
          const timeB = b.createTime.replace(/-/g, '/')
          return new Date(timeA) - new Date(timeB)
        })
        setChartData(sortedData)
      }
    } catch (error) {
      console.error('获取情感数据失败:', error)
      ui.showToast({
        title: '数据获取失败',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }

  // 处理天数选择变化
  const handleDaysChange = (days) => {
    setSelectedDays(days)
    fetchEmotionData(days)
  }

  // 获取列表数据
  const fetchListData = async (page = 1) => {
    setListLoading(true)
    try {
      const result = await getEmotionPageList(page, pageSize)
      if (result.code === 100200) {
        setListData(result.data.records)
        setTotal(result.data.total)
        setCurrentPage(page)
      }
    } catch (error) {
      console.error('获取列表数据失败:', error)
      Taro.showToast({
        title: '列表数据获取失败',
        icon: 'none'
      })
    } finally {
      setListLoading(false)
    }
  }

  // 绘制图表
  const drawChart = (data) => {
    if (!data || data.length === 0) return

    // 使用传统的Canvas API
    const ctx = Taro.createCanvasContext('emotionCanvas')
    if (!ctx) {
      console.error('Canvas上下文获取失败')
      return
    }

    // 获取窗口信息并设置合适的画布尺寸
    const windowInfo = Taro.getWindowInfo()
    const canvasWidth = Math.min(windowInfo.windowWidth * 0.9, 600) // 最大宽度600px
    const canvasHeight = 250 // 增加高度以更好显示曲线
    
    // 清空画布
    ctx.clearRect(0, 0, canvasWidth, canvasHeight)
    
    // 绘制图表
    if (chartType === 'line') {
      drawCurveChart(ctx, data, canvasWidth, canvasHeight)
    } else {
      drawBarChart(ctx, data, canvasWidth, canvasHeight)
    }
    
    // 绘制到Canvas
    ctx.draw()
  }

  // 绘制曲线图
  const drawCurveChart = (ctx, data, width, height) => {
    const padding = 50
    const chartWidth = width - padding * 2
    const chartHeight = height - padding * 2
    
    // 找出分数范围
    const scores = data.map(item => item.score)
    const minScore = Math.min(...scores)
    const maxScore = Math.max(...scores)
    const scoreRange = maxScore - minScore || 1
    
    // 绘制坐标轴
    ctx.setStrokeStyle('#e5e5e5')
    ctx.setLineWidth(1)
    
    // Y轴
    ctx.beginPath()
    ctx.moveTo(padding, padding)
    ctx.lineTo(padding, height - padding)
    ctx.stroke()
    
    // X轴
    ctx.beginPath()
    ctx.moveTo(padding, height - padding)
    ctx.lineTo(width - padding, height - padding)
    ctx.stroke()
    
    // 绘制网格线
    const gridLines = 5
    ctx.setStrokeStyle('#f0f0f0')
    for (let i = 1; i < gridLines; i++) {
      const y = padding + (chartHeight / gridLines) * i
      ctx.beginPath()
      ctx.moveTo(padding, y)
      ctx.lineTo(width - padding, y)
      ctx.stroke()
    }
    
    // 绘制Y轴标签
    ctx.setFillStyle('#666')
    ctx.setFontSize(12)
    ctx.setTextAlign('right')
    for (let i = 0; i <= gridLines; i++) {
      const score = maxScore - (scoreRange / gridLines) * i
      const y = padding + (chartHeight / gridLines) * i
      ctx.fillText(score.toFixed(1), padding - 5, y + 4)
    }
    
    // 绘制数据点和曲线
    if (data.length > 0) {
      const stepX = chartWidth / (data.length - 1 || 1)
      
      // 计算所有点的坐标
      const points = data.map((item, index) => ({
        x: padding + stepX * index,
        y: height - padding - ((item.score - minScore) / scoreRange) * chartHeight,
        emotion: item.emotion,
        score: item.score
      }))
      
      // 绘制平滑曲线
      if (points.length > 1) {
        ctx.setStrokeStyle('#1890ff')
        ctx.setLineWidth(3)
        ctx.beginPath()
        
        // 移动到第一个点
        ctx.moveTo(points[0].x, points[0].y)
        
        if (points.length === 2) {
          // 只有两个点时直接连线
          ctx.lineTo(points[1].x, points[1].y)
        } else {
          // 多个点时使用贝塞尔曲线
          for (let i = 0; i < points.length - 1; i++) {
            const current = points[i]
            const next = points[i + 1]
            
            if (i === 0) {
              // 第一段曲线
              const cp1x = current.x + (next.x - current.x) * 0.5
              const cp1y = current.y
              const cp2x = next.x - (next.x - current.x) * 0.5
              const cp2y = next.y
              ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, next.x, next.y)
            } else {
              // 中间和最后的曲线段
              const prev = points[i - 1]
              const cp1x = current.x + (next.x - prev.x) * 0.3
              const cp1y = current.y + (next.y - prev.y) * 0.3
              const cp2x = next.x - (next.x - current.x) * 0.5
              const cp2y = next.y
              ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, next.x, next.y)
            }
          }
        }
        
        ctx.stroke()
      }
      
      // 绘制数据点
      points.forEach((point) => {
        // 根据情感类型设置不同颜色
        let pointColor = '#1890ff'
        if (point.emotion === '积极') {
          pointColor = '#52c41a'
        } else if (point.emotion === '消极') {
          pointColor = '#ff4d4f'
        } else {
          pointColor = '#faad14'
        }
        
        // 绘制外圈
        ctx.setFillStyle('#fff')
        ctx.beginPath()
        ctx.arc(point.x, point.y, 6, 0, 2 * Math.PI)
        ctx.fill()
        
        // 绘制内圈
        ctx.setFillStyle(pointColor)
        ctx.beginPath()
        ctx.arc(point.x, point.y, 4, 0, 2 * Math.PI)
        ctx.fill()
        
        // 添加边框
        ctx.setStrokeStyle(pointColor)
        ctx.setLineWidth(2)
        ctx.beginPath()
        ctx.arc(point.x, point.y, 6, 0, 2 * Math.PI)
        ctx.stroke()
      })
    }
    
    // 绘制图例
    drawLegend(ctx, width, height)
  }

  // 绘制柱状图
  const drawBarChart = (ctx, data, width, height) => {
    const padding = 40
    const chartWidth = width - padding * 2
    const chartHeight = height - padding * 2
    
    // 找出分数范围
    const scores = data.map(item => item.score)
    const minScore = Math.min(...scores)
    const maxScore = Math.max(...scores)
    const scoreRange = maxScore - minScore || 1
    
    // 绘制坐标轴
    ctx.setStrokeStyle('#e5e5e5')
    ctx.setLineWidth(1)
    
    // Y轴
    ctx.beginPath()
    ctx.moveTo(padding, padding)
    ctx.lineTo(padding, height - padding)
    ctx.stroke()
    
    // X轴
    ctx.beginPath()
    ctx.moveTo(padding, height - padding)
    ctx.lineTo(width - padding, height - padding)
    ctx.stroke()
    
    // 绘制网格线
    const gridLines = 5
    ctx.setStrokeStyle('#f0f0f0')
    for (let i = 1; i < gridLines; i++) {
      const y = padding + (chartHeight / gridLines) * i
      ctx.beginPath()
      ctx.moveTo(padding, y)
      ctx.lineTo(width - padding, y)
      ctx.stroke()
    }
    
    // 绘制Y轴标签
    ctx.setFillStyle('#666')
    ctx.setFontSize(12)
    ctx.setTextAlign('right')
    for (let i = 0; i <= gridLines; i++) {
      const score = maxScore - (scoreRange / gridLines) * i
      const y = padding + (chartHeight / gridLines) * i
      ctx.fillText(score.toFixed(1), padding - 5, y + 4)
    }
    
    // 绘制柱状图
    if (data.length > 0) {
      const barWidth = (chartWidth / data.length) * 0.8
      const barSpacing = (chartWidth / data.length) * 0.2
      
      data.forEach((item, index) => {
        const x = padding + (chartWidth / data.length) * index + barSpacing / 2
        const barHeight = ((item.score - minScore) / scoreRange) * chartHeight
        const y = height - padding - barHeight
        
        // 根据情感类型设置不同颜色
        let barColor = '#1890ff'
        if (item.emotion === '积极') {
          barColor = '#52c41a'
        } else if (item.emotion === '消极') {
          barColor = '#ff4d4f'
        } else {
          barColor = '#faad14'
        }
        
        ctx.setFillStyle(barColor)
        ctx.fillRect(x, y, barWidth, barHeight)
        
        // 绘制分数标签
        ctx.setFillStyle('#666')
        ctx.setFontSize(10)
        ctx.setTextAlign('center')
        ctx.fillText(item.score.toFixed(1), x + barWidth / 2, y - 5)
      })
    }
    
    // 绘制图例
    drawLegend(ctx, width, height)
  }

  // 绘制图例
  const drawLegend = (ctx, width, height) => {
    const legendData = [
      { label: '积极', color: '#52c41a' },
      { label: '中性', color: '#faad14' },
      { label: '消极', color: '#ff4d4f' }
    ]
    
    const legendY = height - 20
    const legendStartX = width - 200
    
    ctx.setFontSize(12)
    ctx.setTextAlign('left')
    
    legendData.forEach((item, index) => {
      const x = legendStartX + index * 60
      
      // 绘制颜色方块
      ctx.setFillStyle(item.color)
      ctx.fillRect(x, legendY - 8, 12, 12)
      
      // 绘制标签
      ctx.setFillStyle('#666')
      ctx.fillText(item.label, x + 16, legendY + 2)
    })
  }

  // 切换图表类型
  const toggleChartType = () => {
    const newType = chartType === 'line' ? 'bar' : 'line'
    setChartType(newType)
  }

  // 处理分页
  const handlePageChange = (page) => {
    if (page < 1 || page > Math.ceil(total / pageSize) || page === currentPage) return
    fetchListData(page)
  }

  // 格式化情感标签颜色
  const getEmotionColor = (emotion) => {
    switch (emotion) {
      case '积极': return '#52c41a'
      case '消极': return '#ff4d4f'
      case '中性': return '#faad14'
      default: return '#1890ff'
    }
  }

  // 格式化时间显示
  const formatTime = (timeStr) => {
    return timeStr.replace(/:\d{2}$/, '') // 去掉秒数，只显示到分钟
  }

  // 监听visible变化，显示时获取数据
  useEffect(() => {
    if (visible) {
      fetchEmotionData()
      fetchListData(1)
    }
  }, [visible])

  // 监听chartData变化，重新绘制图表
  useEffect(() => {
    if (chartData.length > 0 && visible) {
      setTimeout(() => drawChart(chartData), 300)
    }
  }, [chartData, chartType, visible])

  return (
    <View className={`emotion-chart-overlay ${visible ? 'visible' : ''}`} onClick={onClose}>
      <View className={`emotion-chart-drawer ${visible ? 'visible' : ''}`} onClick={(e) => e.stopPropagation()}>
        <View className="emotion-chart-header">
          <View className="emotion-chart-title">情感分析趋势</View>
          <View className="emotion-chart-actions">
            <View className="days-selector">
              {daysOptions.map((option) => (
                <View
                  key={option.value}
                  className={`days-btn ${selectedDays === option.value ? 'active' : ''}`}
                  onClick={() => handleDaysChange(option.value)}
                >
                  {option.label}
                </View>
              ))}
            </View>
            <View 
              className="chart-type-btn"
              onClick={toggleChartType}
            >
              {chartType === 'line' ? '柱状图' : '曲线图'}
            </View>
            <View className="close-btn" onClick={onClose}>✕</View>
          </View>
        </View>
        
        <View className="emotion-chart-container">
          {/* 图表部分 */}
          <View className="emotion-chart-content">
            {loading ? (
              <View className="loading-container">
                <View className="loading-text">图表加载中...</View>
              </View>
            ) : (
              isH5() ? (
                <EChartsComponent 
                  data={chartData}
                  chartType={chartType}
                  width="100%"
                  height="250px"
                />
              ) : (
                <Canvas
                  canvasId="emotionCanvas"
                  className="emotion-canvas"
                  style={{width: '100%', height: '250px'}}
                />
              )
            )}
          </View>
          
          {/* 列表部分 */}
          <View className="emotion-list-section">
            <View className="emotion-list-header">
              <View className="section-title">情感得分记录</View>
              <View className="list-summary">共 {total} 条记录</View>
            </View>
            
            {listLoading ? (
              <View className="loading-container">
                <View className="loading-text">列表加载中...</View>
              </View>
            ) : (
              <ScrollView className="emotion-list-container" scrollY>
                {listData.map((item) => (
                  <View key={item.id} className="emotion-list-item">
                    <View className="list-item-header">
                      <View 
                        className="emotion-tag"
                        style={{ backgroundColor: getEmotionColor(item.emotion) }}
                      >
                        {item.emotion}
                      </View>
                      <View className="emotion-score">{item.score.toFixed(1)}</View>
                    </View>
                    <View className="emotion-context">{item.context}</View>
                    <View className="emotion-time">{formatTime(item.createTime)}</View>
                  </View>
                ))}
              </ScrollView>
            )}
            
            {/* 分页器 */}
            {total > pageSize && (
              <View className="pagination">
                <View 
                  className={`page-btn ${currentPage === 1 ? 'disabled' : ''}`}
                  onClick={() => handlePageChange(currentPage - 1)}
                >
                  上一页
                </View>
                
                <View className="page-info">
                  {currentPage} / {Math.ceil(total / pageSize)}
                </View>
                
                <View 
                  className={`page-btn ${currentPage === Math.ceil(total / pageSize) ? 'disabled' : ''}`}
                  onClick={() => handlePageChange(currentPage + 1)}
                >
                  下一页
                </View>
              </View>
            )}
          </View>
        </View>
      </View>
    </View>
  )
}